package com.mobilepay.moneypig.model.activity.mine;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseActivity;
import com.mobilepay.moneypig.base.NoDoubleClickListener;
import com.mobilepay.moneypig.config.DIR;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.model.dialog.PhotoChooseDialog;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.mine.IdentifyPictureData;
import com.mobilepay.moneypig.response.mine.UserDetailData;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.utils.IDCard;
import com.mobilepay.moneypig.utils.SysUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xlm on 2017/7/26 0026
 */

public class IdentifyActivity extends BaseActivity {
    private static final String TAG = "IdentifyActivity";
    private RelativeLayout mRelativeBack;
    private EditText mEditNumber, mEditName;
    private ImageView mImageFace, mImageRevese, mImageHand;
    private TextView mTextFace, mTextRevese, mTextHand;
    private Button mButtonCommit;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_identify);
    }

    @Override
    protected void initViews() {
        mRelativeBack = (RelativeLayout) findViewById(R.id.identify_back);

        mEditName = (EditText) findViewById(R.id.identify_name);
        mEditNumber = (EditText) findViewById(R.id.identify_number);

        mImageFace = (ImageView) findViewById(R.id.image_type);
        mImageRevese = (ImageView) findViewById(R.id.image_type2);
        mImageHand = (ImageView) findViewById(R.id.image_type3);

        mTextFace = (TextView) findViewById(R.id.type_button);
        mTextRevese = (TextView) findViewById(R.id.type2_button);
        mTextHand = (TextView) findViewById(R.id.type3_button);

        mButtonCommit = (Button) findViewById(R.id.idenfity_commit);
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {

    }

    @Override
    protected void onSetListener() {
        mRelativeBack.setOnClickListener(this);
        mImageFace.setOnClickListener(this);
        mImageRevese.setOnClickListener(this);
        mImageHand.setOnClickListener(this);
        mTextFace.setOnClickListener(this);
        mTextRevese.setOnClickListener(this);
        mTextHand.setOnClickListener(this);
        mButtonCommit.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                super.onNoDoubleClick(view);
                checkDataCompare();
            }
        });

//        //只输入身份证号数字
//        mEditNumber.setKeyListener(new NumberKeyListener() {
//            @Override
//            public int getInputType() {
//                return android.text.InputType.TYPE_CLASS_PHONE;
//            }
//
//            @Override
//            protected char[] getAcceptedChars() {
//                return new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'X'};
//            }
//        });

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.identify_back:
                finish();
                break;
            case R.id.type_button:
            case R.id.image_type:
                showPhotoChooseDialog1();
                break;
            case R.id.image_type2:
            case R.id.type2_button:
                showPhotoChooseDialog2();
                break;
            case R.id.image_type3:
            case R.id.type3_button:
                showPhotoChooseDialog3();
                break;
        }
    }

    public void checkDataCompare() {
        if (CommonUtil.isEmpty(mEditName.getText().toString())) {
            showToastShort("请输入姓名");
        } else if (CommonUtil.isEmpty(mEditNumber.getText().toString())) {
            showToastShort("请输入身份证号");
        } else if (CommonUtil.isEmpty(photo_1)) {
            showToastShort("请添加身份证正面");
        } else if (CommonUtil.isEmpty(photo_2)) {
            showToastShort("请添加身份证反面");
        } else if (CommonUtil.isEmpty(photo_3)) {
            showToastShort("请添加身份证手持照");
        } else {
            commitImages();
//            if (!IDCard.IDCardValidate(mEditNumber.getText().toString())) {
//                showToastShort("身份证号不合法");
//            } else {
//                commitImages();
//            }
        }
    }

    String path = DIR.TEMP_CAMERA;

    private final static int CAMERA_1 = 3;
    private final static int CAMERA_2 = 4;
    private final static int CAMERA_3 = 5;

    String photoPath;

    private void takeCamera1() {
        photoPath = path + CommonUtil.getCurrentMS() + ".jpg";
        SysUtil.startCamera(this, new File(photoPath), CAMERA_1);
    }

    private void takeCamera2() {
        photoPath = path + CommonUtil.getCurrentMS() + ".jpg";
        SysUtil.startCamera(this, new File(photoPath), CAMERA_2);
    }

    private void takeCamera3() {
        photoPath = path + CommonUtil.getCurrentMS() + ".jpg";
        SysUtil.startCamera(this, new File(photoPath), CAMERA_3);
    }

    private void takePhoto1() {
        SysUtil.choosePhoto(this, PHOTO_1);
    }

    private void takePhoto2() {
        SysUtil.choosePhoto(this, PHOTO_2);
    }

    private void takePhoto3() {
        SysUtil.choosePhoto(this, PHOTO_3);
    }

    private final static int PHOTO_1 = 0;
    private final static int PHOTO_2 = 1;
    private final static int PHOTO_3 = 2;

    private String photo_1;
    private String photo_2;
    private String photo_3;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //相册
                case PHOTO_1:
                    photo_1 = SysUtil.getRealpathFromUri(this, data.getData());
                    Glide.with(this).load(photo_1).into(mImageFace);
                    CommonUtil.getimage(photo_1);
                    break;
                case PHOTO_2:
                    photo_2 = SysUtil.getRealpathFromUri(this, data.getData());
                    Glide.with(this).load(photo_2).into(mImageRevese);
                    CommonUtil.getimage(photo_2);
                    break;
                case PHOTO_3:
                    photo_3 = SysUtil.getRealpathFromUri(this, data.getData());
                    Glide.with(this).load(photo_3).into(mImageHand);
                    CommonUtil.getimage(photo_3);
                    break;
                //相机
                case CAMERA_1:
                    photo_1 = photoPath;
                    Glide.with(this).load(photoPath).into(mImageFace);
                    CommonUtil.getimage(photo_1);
                    break;
                case CAMERA_2:
                    photo_2 = photoPath;
                    Glide.with(this).load(photoPath).into(mImageRevese);
                    CommonUtil.getimage(photo_2);
                    break;
                case CAMERA_3:
                    photo_3 = photoPath;
                    Glide.with(this).load(photoPath).into(mImageHand);
                    CommonUtil.getimage(photo_3);
                    break;
            }
        }
    }

    private PhotoChooseDialog mPhotoChooseDialog1;
    private static final int PERMISSON_CAMER = 1;

    private void showPhotoChooseDialog1() {
        if (mPhotoChooseDialog1 == null) {
            mPhotoChooseDialog1 = new PhotoChooseDialog(this);
            mPhotoChooseDialog1.setListener(new PhotoChooseDialog.Listener() {
                @Override
                public void onSelectedCamera() {
                    checkPermission();
                }

                @Override
                public void onSelectedDCIM() {
                    takePhoto1();
                }
            });
        }
        mPhotoChooseDialog1.show();
    }

    /**
     * 检查权限，因为android6.0有些权限需要用户确认授权
     */

    private void checkPermission() {
        if (checkCameraPermission(PERMISSON_CAMER)) {
            takeCamera1();
        }
    }

    @Override
    public void onCameraPermission(int result_code, boolean result) {
        if (result) {
            checkPermission();
        } else {
            showToastShort("拒绝相机功能，您将不能通过相机拍照");
        }
    }

    private PhotoChooseDialog mPhotoChooseDialog2;

    private void showPhotoChooseDialog2() {
        if (mPhotoChooseDialog2 == null) {
            mPhotoChooseDialog2 = new PhotoChooseDialog(this);
            mPhotoChooseDialog2.setListener(new PhotoChooseDialog.Listener() {
                @Override
                public void onSelectedCamera() {
                    takeCamera2();
                }

                @Override
                public void onSelectedDCIM() {
                    takePhoto2();
                }
            });
        }
        mPhotoChooseDialog2.show();
    }

    private PhotoChooseDialog mPhotoChooseDialog3;

    private void showPhotoChooseDialog3() {
        if (mPhotoChooseDialog3 == null) {
            mPhotoChooseDialog3 = new PhotoChooseDialog(this);
            mPhotoChooseDialog3.setListener(new PhotoChooseDialog.Listener() {
                @Override
                public void onSelectedCamera() {
                    takeCamera3();
                }

                @Override
                public void onSelectedDCIM() {
                    takePhoto3();
                }
            });
        }
        mPhotoChooseDialog3.show();
    }

//    AppID: 10099467
//    SecretID: AKID398wiOoFWgkmniJK1YHvSvKdpwxr2M2d
//    SecretKey: eIvRrKj2GOPNF2iJoEgz73pQq581jFex


    //图片上传
    private void commitImages() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.upload_image);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("module", "user");
        param.add("driver", "app");
        param.add("return_type", "json");
        param.add("cardsz_img", new File(photo_1));
        param.add("cardsf_img", new File(photo_2));
        param.add("cardssc_img", new File(photo_3));
        //签名算法
        Map<String, String> map = new HashMap<>();
        map.put("return_type", "json");
        map.put("method", NetConfig.upload_image);
        map.put("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        map.put("module", "user");
        map.put("driver", "app");
        param.add("sign", CommonUtil.toAscIIMd5String(map, true));
        showProgress("资料上传中");
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                //对图片id赋值
                dismissProgress();
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        IdentifyPictureData data = GsonUtil.GsonToBean(string, IdentifyPictureData.class);
                        card_z = String.valueOf(data.getData().getCardsz_img());
                        card_f = String.valueOf(data.getData().getCardsf_img());
                        card_sc = String.valueOf(data.getData().getCardssc_img());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                commitData();
                            }
                        });
                    }
                }
            }
        });
    }


    private String card_z;
    private String card_f;
    private String card_sc;

    //提交认证资料
    private void commitData() {
        if (CommonUtil.isEmpty(card_z) || CommonUtil.isEmpty(card_f) || CommonUtil.isEmpty(card_sc)) {
            dismissProgress();
            showToastShort("提交失败,请重试");
            return;
        }
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.cert);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("real_name", mEditName.getText().toString());
        param.add("cards_code", mEditNumber.getText().toString());
        param.add("cardsz_img", String.valueOf(card_z));
        param.add("cardsf_img", String.valueOf(card_f));
        param.add("cardssc_img", String.valueOf(card_sc));
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                if (CommonUtil.isForeground(IdentifyActivity.this)) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissProgress();
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    showToastShort(responseResult.getInfo());
                    if (responseResult.getStatus() == 1) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                getUserDetail();
                            }
                        });
                    }
                }
            }
        });
    }


    //账户信息
    private void getUserDetail() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.get_detail);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                if (CommonUtil.isForeground(IdentifyActivity.this)) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        UserDetailData data = GsonUtil.GsonToBean(string, UserDetailData.class);
                        App.getApp().setUserDetailInfo(data);//保存账户信息
                    } else {
                        showToastShort(responseResult.getInfo());
                    }
//                    EventBus.getDefault().post(new UpdateDataEvent());//更新用户信息
                    finishActivity(false);
                }
            }
        });
    }

}
